package com.tfxy.hxl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tfxy.hxl.R;
import com.tfxy.hxl.entity.Coach;
import com.tfxy.hxl.service.CoachService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/coach")
public class CoachController {

    @Autowired
    private CoachService coachService;

    // 创建教练
    @PostMapping("/create")
    public R createCoach(@RequestBody Coach coach) {
        coach.setCreateTime(new Date());
        coach.setUpdateTime(new Date());
        coach.setStatus(1); // 默认启用
        boolean saved = coachService.save(coach);
        return saved ? R.ok().message("教练创建成功") : R.error().message("教练创建失败");
    }

    // 分页查询教练列表
    @GetMapping("/list")
    public R getCoachList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name) {

        Page<Coach> page = new Page<>(current, size);
        QueryWrapper<Coach> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);

        if (name != null && !name.trim().isEmpty()) {
            queryWrapper.like("name", name);
        }

        queryWrapper.orderByDesc("create_time");
        Page<Coach> result = coachService.page(page, queryWrapper);

        return R.ok()
                .data("coaches", result.getRecords())
                .data("total", result.getTotal())
                .data("current", result.getCurrent())
                .data("size", result.getSize());
    }

    // 查询教练详情
    @GetMapping("/{id}")
    public R getCoachById(@PathVariable Long id) {
        Coach coach = coachService.getById(id);
        return coach != null ? R.ok().data("coach", coach) : R.error().message("教练不存在");
    }

    // 更新教练信息
    @PutMapping("/update")
    public R updateCoach(@RequestBody Coach coach) {
        coach.setUpdateTime(new Date());
        boolean updated = coachService.updateById(coach);
        return updated ? R.ok().message("教练更新成功") : R.error().message("教练更新失败");
    }

    // 删除教练
    @DeleteMapping("/{id}")
    public R deleteCoach(@PathVariable Long id) {
        boolean removed = coachService.removeById(id);
        return removed ? R.ok().message("教练删除成功") : R.error().message("教练删除失败");
    }

    // 停用/启用教练
    @PutMapping("/toggle-status/{id}")
    public R toggleCoachStatus(@PathVariable Long id) {
        Coach coach = coachService.getById(id);
        if (coach == null) {
            return R.error().message("教练不存在");
        }
        coach.setStatus(coach.getStatus() == 1 ? 0 : 1);
        boolean updated = coachService.updateById(coach);
        return updated ? R.ok().message("状态更新成功") : R.error().message("状态更新失败");
    }
}
